package com.xzkydz.modle;

import android.support.annotation.Nullable;
import android.util.Log;

import com.google.gson.Gson;
import com.xzkydz.app.MyApp;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class Submit implements ISubmit {

    OnBackListener onBackListener;

    @Override
    public void send(Object o) {
        final String TAG = "asdSend";
        Gson gson = new Gson();
        String parStr = gson.toJson(o);
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), parStr);
        Request request = new Request.Builder()
                .url(MyApp.getInstance().urlStr)
                .post(body)
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();

        okHttpClient.newCall(request).enqueue(new okhttp3.Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {
//                Log.d(TAG, "onFailure: " + e.getMessage());
                if (onBackListener != null) {
                    onBackListener.getFailure(e.getMessage());
                }
            }

            @Override
            public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
                Log.d(TAG, response.protocol() + " " + response.code() + " " + response.message());
                String string = response.body().string();
                Log.d(TAG, "onResponse: " + string);
                onBackListener.getResponse(string);
            }
        });
    }

    public void setOnBackListener(@Nullable OnBackListener l) {
        this.onBackListener = l;
    }

    public interface OnBackListener {
        void getResponse(String response);

        void getFailure(String failure);

    }
}
